package com.lz.service.smsmail.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.Gson;
import com.lz.service.common.response.CommonServiceResponseEnum;
import com.lz.service.common.response.ResponseBody;
import com.lz.service.smsmail.common.Constants;

/**
 * 流量限制 过滤器
 * @author likejian
 *
 */
@WebFilter(filterName="flowLimitFilter",urlPatterns="/*")
public class FlowLimitFilter implements Filter{

	private static final Logger LOG = LoggerFactory.getLogger(FlowLimitFilter.class);
	private static final Gson GSON = new Gson();
	private static RateLimiter RATE_LIMITER = null;
	
	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException,
			ServletException{
		if(RATE_LIMITER == null){
			//RATE_LIMITER = RateLimiter.create(Config.FLOW_LIMIT_PERMITS_PERSECOND);	//限制每秒多少个请求
			RATE_LIMITER = RateLimiter.create(10000);
		}
		if (RATE_LIMITER.tryAcquire()) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}else{
			LOG.warn("====================Over flow limit====================");
			HttpServletResponse response = (HttpServletResponse)servletResponse;
			ResponseBody responseBody = new ResponseBody(CommonServiceResponseEnum.OVER_FLOW_LIMIT);
			response.setContentType(Constants.CONTEN_TTYPE_JSON);
			response.setCharacterEncoding(Constants.ENCODING_UTF8);
			response.setStatus(403);
			PrintWriter out = servletResponse.getWriter();
			out.println(GSON.toJson(responseBody));
			out.flush();
			out.close();
			return;
		}
	}
	
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
